<?php
class EsSoapClient extends SoapClient{
	
}

function es_initServerList($api_url){
	$apiUrl = $api_url;
	$apiUrl = parse_url($apiUrl);
	
	$AllowSites = array(
						'member.emailserving.test',
						'member.emailserving.com'
						);
	$AllowFlag = false;

	if(
		($apiUrl['scheme'] == 'http' || $apiUrl['scheme'] == 'https') &&
		 in_array($apiUrl['host'], $AllowSites) &&
		 strpos($apiUrl['path'], 'api/index/soap/key/') &&
		 $apiUrl['query'] == 'wsdl'
		){
		$AllowFlag = true;
	}else{
		return false;
	}
	
	$rs = array();
		
	try{
		$EsSoap = new EsSoapClient($api_url);
		
		$fields = array("email_address", "first_name", "last_name");
		
		$esSyncUrl = es_getSyncUrl();
		$esSyncKey = get_option('es_api_key');
		$esSyncUrl = $esSyncUrl.'&key='.$esSyncKey;
		
		$rs = $EsSoap->createRegisterMagicSyncListAndSync($esSyncUrl, $fields);
		$rs["campainies"] = $EsSoap->getAllCampaignsByRegisterMagicSync();
		
		if($apiUrl['host'] == "member.emailserving.com") {
			$rs['server_type'] = "com";
		}else{
			$rs['server_type'] = "test";
		}
	}
	catch(Exception $ex){
		return null;
	}
	return $rs;
}


function es_getCampaignReport($api_url, $campaignId){
	$apiUrl = $api_url;
	$apiUrl = parse_url($apiUrl);
	
	$AllowSites = array(
						'member.emailserving.test',
						'member.emailserving.com'
						);
	$AllowFlag = false;

	if(
		($apiUrl['scheme'] == 'http' || $apiUrl['scheme'] == 'https') &&
		 in_array($apiUrl['host'], $AllowSites) &&
		 strpos($apiUrl['path'], 'api/index/soap/key/') &&
		 $apiUrl['query'] == 'wsdl'
		){
		$AllowFlag = true;
	}else{
		return false;
	}
	
	$rs = array();
	try{
		
		$EsSoap = new EsSoapClient($api_url);
		
		$fields = array("email_address", "first_name", "last_name");
		
		$esSyncUrl = es_getSyncUrl();
		$esSyncKey = get_option('es_api_key');
		$esSyncUrl = $esSyncUrl.'&key='.$esSyncKey;
		
		if(!empty($campaignId))
			$rs = $EsSoap->getCampaignReport($campaignId);
		
		if($apiUrl['host'] == "member.emailserving.com") {
			$rs['server_type'] = "com";
		}else{
			$rs['server_type'] = "test";
		}
		
	}
	catch(Exception $ex){
		return null;
	}
	return $rs;
}


function es_getSyncUrl(){
	$site_url = get_option('siteurl');
	$sync_page_id = get_option('es_sync_post_id');
	
	if(!empty($sync_page_id)){
		$syncUrl = $site_url . '/?page_id=' . $sync_page_id ;
		return $syncUrl;
	}else{
		return false;
	}
}

function es_getUrlType($apiUrl){
	$rs = "test";
	if(!empty($apiUrl)){
		if(!is_array($apiUrl)){
			$apiUrl = parse_url($apiUrl);
		}
		if($apiUrl['host'] == "member.emailserving.com") {
			$rs = "com";
		}else{
			$rs = "test";
		}
	}
	return $rs;
}


